package forms;

import DAO.CategoriasDAO;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import model.Categorias;

public class frmCategoriaProduto extends javax.swing.JFrame {
boolean alterar = false;
    /**
     * Creates new form CategoriaProduto
     */
    public frmCategoriaProduto() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jMenuItem1 = new javax.swing.JMenuItem();
        TabPai = new javax.swing.JTabbedPane();
        TabListagem = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabCategoria = new javax.swing.JTable();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel17 = new javax.swing.JLabel();
        txtFiltroNome = new javax.swing.JTextField();
        btnBuscar = new javax.swing.JButton();
        btnNovo = new javax.swing.JButton();
        btnAlterar = new javax.swing.JButton();
        btnDeletar = new javax.swing.JButton();
        TabCadastro = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtNome = new javax.swing.JTextField();
        radAtivo = new javax.swing.JRadioButton();
        radInativo = new javax.swing.JRadioButton();
        btnGravar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        lblCodigo = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();

        jMenuItem1.setText("jMenuItem1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        TabPai.setPreferredSize(new java.awt.Dimension(700, 600));

        TabListagem.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        tabCategoria.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Código:", "Nome:", "Status:"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tabCategoria);

        TabListagem.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, 760, 256));
        TabListagem.add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 60, 800, 10));

        jLabel17.setText("Nome:");
        TabListagem.add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
        TabListagem.add(txtFiltroNome, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 236, -1));

        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });
        TabListagem.add(btnBuscar, new org.netbeans.lib.awtextra.AbsoluteConstraints(690, 10, -1, 40));

        btnNovo.setText("Novo");
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });
        TabListagem.add(btnNovo, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 330, 135, -1));

        btnAlterar.setText("Alterar");
        btnAlterar.setPreferredSize(new java.awt.Dimension(57, 23));
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });
        TabListagem.add(btnAlterar, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 330, 135, -1));

        btnDeletar.setText("Deletar");
        btnDeletar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeletarActionPerformed(evt);
            }
        });
        TabListagem.add(btnDeletar, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 330, 140, -1));

        TabPai.addTab("Listagem", TabListagem);

        jLabel2.setText("Nome");

        jLabel3.setText("Status:");

        buttonGroup1.add(radAtivo);
        radAtivo.setText("Ativo");

        buttonGroup1.add(radInativo);
        radInativo.setText("Inativo");

        btnGravar.setText("Salvar");
        btnGravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGravarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        lblCodigo.setText("0");

        javax.swing.GroupLayout TabCadastroLayout = new javax.swing.GroupLayout(TabCadastro);
        TabCadastro.setLayout(TabCadastroLayout);
        TabCadastroLayout.setHorizontalGroup(
            TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(TabCadastroLayout.createSequentialGroup()
                .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(TabCadastroLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lblCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(TabCadastroLayout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(TabCadastroLayout.createSequentialGroup()
                                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(7, 7, 7)
                                .addComponent(btnGravar, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(TabCadastroLayout.createSequentialGroup()
                                    .addComponent(jLabel3)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(radAtivo)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(radInativo))
                                .addGroup(TabCadastroLayout.createSequentialGroup()
                                    .addComponent(jLabel2)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 460, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                .addContainerGap(255, Short.MAX_VALUE))
        );
        TabCadastroLayout.setVerticalGroup(
            TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(TabCadastroLayout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(lblCodigo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(radAtivo)
                    .addComponent(radInativo))
                .addGap(18, 18, 18)
                .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnCancelar)
                    .addComponent(btnGravar))
                .addContainerGap(230, Short.MAX_VALUE))
        );

        TabPai.addTab("Cadastro", TabCadastro);

        getContentPane().add(TabPai, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 780, 390));

        jMenu1.setText("Fechar");
        jMenu1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu1MouseClicked(evt);
            }
        });
        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGravarActionPerformed
        if (txtNome.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Campo Nome da Unidade de Medida É Necessário!");
            txtNome.requestFocus();
        } else {
            try {
                int CTG_ID = Integer.parseInt(lblCodigo.getText());
                String CTG_NOME = txtNome.getText();
                boolean CTG_STATUS;
                if (radAtivo.isSelected()) {
                    CTG_STATUS = true;
                } else {
                    CTG_STATUS = false;
                }
                Categorias ctg = new Categorias();
                ctg.setCodigo(CTG_ID);
                ctg.setNome(CTG_NOME);
                ctg.setStatus(CTG_STATUS);
                CategoriasDAO dao = new CategoriasDAO();
                if (alterar == false) {
                dao.insert(ctg);
                JOptionPane.showMessageDialog(this, "Categoria Salva!");
            } else {
                dao.update(ctg);
                JOptionPane.showMessageDialog(this, "Categoria Alterada!");
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
            atualizagrid();
            txtNome.setText("");
            TabPai.setSelectedIndex(0);
        }
    }//GEN-LAST:event_btnGravarActionPerformed
private void atualizagrid() {
        DefaultTableModel modelo = (DefaultTableModel) tabCategoria.getModel();
        modelo.setNumRows(0);
        try {
            CategoriasDAO dao = new CategoriasDAO();
            for (Categorias c : dao.findAll()) {

                modelo.addRow(
                        new String[]{
                            "" + c.getCodigo(),
                            c.getNome(),
                            c.isStatus()?"Ativo":"Inativo"});
            }
        } catch (Exception ex) {
        }
    }
    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        alterar = false;
        TabPai.setSelectedIndex(1);
    }//GEN-LAST:event_btnNovoActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        alterar = true;

        String codigo = "" + tabCategoria.getValueAt(tabCategoria.getSelectedRow(), 0);
        try {
            CategoriasDAO DAO = new CategoriasDAO();
            Categorias u = DAO.findByCodigo(Integer.parseInt(codigo));
            lblCodigo.setText(codigo);
            txtNome.setText(u.getNome());
            if(u.isStatus()){
            radAtivo.setSelected(true);
            }
            else{
            radInativo.setSelected(true);
            }
        } catch (Exception ex) {
            Logger.getLogger(frmUnidadeMedida.class.getName()).log(Level.SEVERE, null, ex);
        }
        atualizagrid();
        TabPai.setSelectedIndex(1);
        
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        lblCodigo.setText("0");
        txtNome.setText("");
        TabPai.setSelectedIndex(0);
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
    lblCodigo.setVisible(false);
    radAtivo.setSelected(true);
    atualizagrid();
    }//GEN-LAST:event_formWindowOpened

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
    DefaultTableModel modelo = (DefaultTableModel) tabCategoria.getModel();
        modelo.setNumRows(0);
        try {
            CategoriasDAO dao = new CategoriasDAO();
            for (Categorias c : dao.findByNome(txtFiltroNome.getText())) {

                modelo.addRow(
                        new String[]{
                            "" + c.getCodigo(),
                            c.getNome(),
                            c.isStatus()?"Ativo":"Inativo"});
            }
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void btnDeletarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeletarActionPerformed
String codigo = "" + tabCategoria.getValueAt(tabCategoria.getSelectedRow(), 0);
        try {
            CategoriasDAO DAO = new CategoriasDAO();
            DAO.delete(Integer.parseInt(codigo));
        } catch (Exception ex) {
            Logger.getLogger(frmUnidadeMedida.class.getName()).log(Level.SEVERE, null, ex);
        }
        atualizagrid();
    }//GEN-LAST:event_btnDeletarActionPerformed

    private void jMenu1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu1MouseClicked
this.dispose();
    }//GEN-LAST:event_jMenu1MouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new frmCategoriaProduto().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel TabCadastro;
    private javax.swing.JPanel TabListagem;
    private javax.swing.JTabbedPane TabPai;
    private javax.swing.JButton btnAlterar;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnDeletar;
    private javax.swing.JButton btnGravar;
    private javax.swing.JButton btnNovo;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JRadioButton radAtivo;
    private javax.swing.JRadioButton radInativo;
    private javax.swing.JTable tabCategoria;
    private javax.swing.JTextField txtFiltroNome;
    private javax.swing.JTextField txtNome;
    // End of variables declaration//GEN-END:variables
}
